package com.zadetk.helpyou.activities;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.zadetk.helpyou.R;
import com.zadetk.helpyou.bean.UpdateInfo;
import com.zadetk.helpyou.net.BaseObserver;
import com.zadetk.helpyou.net.BaseResponse;
import com.zadetk.helpyou.net.LoadApkAsyncTask;
import com.zadetk.helpyou.net.NetTool;
import com.zadetk.helpyou.other.Const;
import com.zadetk.helpyou.utils.VersionUtils;

import java.io.File;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 1-0启动页
 */
public class SplashActivity extends AppCompatActivity implements View.OnClickListener{

    private ImmersionBar bar;
    private Handler handler;
    private UpdateInfo update_info;

    private int recLen = 5; //跳过倒计时提示5秒
    private TextView pass;
    Timer timer = new Timer();
    private Handler timeHandler;
    private Runnable runnable;
    boolean clicked = true;

    protected Handler loadApkHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LoadApkAsyncTask.LOAD_APK:
                    if ((Boolean) msg.obj) {
                        VersionUtils.installApk(SplashActivity.this, new File(
                                Const.getSavePath(SplashActivity.this), LoadApkAsyncTask.UPDATE_APK_NAME));
                    } else {
                        showUpdateDialog(update_info, "错误提示", "下载失败，请重新下载？");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        int flag= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        //设置当前窗体为全屏显示
        getWindow().setFlags(flag, flag);
        setContentView(R.layout.activity_splash);
        initView();
        timer.schedule(task, 1000, 1000);//等待时间一秒，停顿时间一秒

        timeHandler = new Handler();
        timeHandler.postDelayed(runnable = new Runnable() {
            @Override
            public void run() {
                //从闪屏界面跳转到首界面
                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        }, 5000);


//        handler = new Handler() {
//            @Override
//            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
//
//                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
//                    finish();
//
//            }
//        };
        bar = ImmersionBar.with(this);
        bar.init();
        //updateApk();
 //       handler.sendEmptyMessageDelayed(0, 5000);
    }

    private void initView() {
        pass = findViewById(R.id.tv_pass);//跳过
        pass.setOnClickListener((View.OnClickListener) this);//跳过监听
    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() { // UI thread
                @Override
                public void run() {
                    recLen--;
                    pass.setText("跳过 " + recLen);
                    if (recLen < 0) {
                        timer.cancel();
                        pass.setVisibility(View.GONE);//倒计时到0隐藏字体
                    }
                }
            });
        }
    };


    @Override
    protected void onDestroy() {
        if (bar != null) bar.destroy();
        super.onDestroy();
    }

    private void updateApk() {

        Map<String, Object> params = NetTool.newParams();
        //params.put("uid", AppPreferenceUtil.getUserId(mActivity));
        NetTool.getApi().checkUpdate(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<UpdateInfo>>() {
                    @Override
                    public void onData(BaseResponse<UpdateInfo> value) {
                        UpdateInfo info;
                        if (value != null && (info = value.getData()) != null) {
                            update_info = info;
                            int localVersionCode = VersionUtils.getAppVersionCode(SplashActivity.this);
                            int remoteVersionCode = info.getNumber();
                            if (remoteVersionCode > localVersionCode) {
                                showUpdateDialog(info, "版本升级", "发现新版本！");
                            } else {
                                handler.sendEmptyMessageDelayed(0, 2000);
                            }
                        }
                    }
                });
    }

    protected void showUpdateDialog(final UpdateInfo updateApkInfo, String titleStr, String msgStr) {
        android.app.AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity.this);
        builder.setTitle(titleStr);
        builder.setMessage(msgStr);
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                new LoadApkAsyncTask(SplashActivity.this, "下载中...", loadApkHandler)
                        .execute(updateApkInfo.getUrl(),
                                String.valueOf(updateApkInfo.getNumber()));
            }
        });

        if (updateApkInfo.getIsForce() == 2) {
            builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.cancel();
                }
            });
        }
        Dialog dialog = builder.create();
        dialog.show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_pass:
                //从闪屏界面跳转到首界面
                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                if (runnable != null) {
                    timeHandler.removeCallbacks(runnable);
                }
                break;
            default:
                break;
        }
    }
}
